from flask import Blueprint,render_template,request
from common.libs.Helper import ops_renderJSON,ops_renderErrJSON,ops_render
from common.models.document import Document
from application import db
from flask import request,json
from qiniu import Auth
from qiniu import put_data
import time

document_page = Blueprint( "document_page",__name__ )

@document_page.route('/', methods=['GET', 'POST'])
def index():
    return ops_render("/common/document.html")

@document_page.route('/post', methods=['GET', 'POST'])
def document_post():
    content = request.form.get('content')
    title = request.form.get('title')
    type = request.form.get('type')
    classone = request.form.get('classone')
    image = request.form.get('image')
    document = Document()
    document.content = content
    document.type = type
    document.title = title
    document.classone = classone
    document.image=image
    db.session.add(document)
    db.session.commit()
    return ops_render("/common/document.html")



@document_page.route('/submitimage', methods=['GET', 'POST'])
def submitImage():
    file = request.files['file']
    # 上传到七牛后保存的文件名
    key=str(int(time.time()))+file.filename
    # print file.filename
    access_key = 'po98t2WFtFrNvPJ_bZTFobndhhKhQUk6mrXq2NX1'
    secret_key = 'DbooW85jje3wtiDP0se_JLL76PjgLGc-3p2fiEaZ'
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'guanzhuoran'
    #http://+外链域名
    domian_name = 'http://upload.guanzhuoran.cn/'
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)
    # ret, info = _form_put(token, key, file.read(),params=None,
    #          mime_type='application/octet-stream', crc=None)

    ret, info=put_data(token, key, file.read(),params=None,
              mime_type='application/octet-stream')
    print(info)
    print(ret['key'])
    return '{"location":"'+domian_name+"/"+key+'"}'


@document_page.route('/getimg', methods=['GET', 'POST'])
def getImg():
    req = request.values
    type = req['type'] if "type" in req else "默认"
    a = Document.query.filter_by(type="首页新闻",company=type).all()
    rts = []
    for item in a:
        temp = dict(image=item.image)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts
